/**
 * 
 */
package gui;

import helper.TableHelper;

import java.awt.event.ItemEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import table.CheckboxEditor;
import table.CheckboxRenderer;
import table.ComboboxEditor;
import table.ComboboxRenderer;
import table.DesignTableModel;
import table.TableModel;
import tree.IconData;
import view.View;
import combobox.*;

/**
 * @author Ken
 *
 */
public class CodeBehind {
	public static Form f;
	public static InputForm input;
	public static View view;
	public static AccountForm af;
	public static List<AccountStruct> accountList;
	
	public static void exit() {
		// TODO Auto-generated method stub		
	}

	public static void createDatabase() {
		f.setEnabled(false);
		input.setVisible(true);
		input.type = 0;
		input.reset();
	}

	public static void deleteDatabase() {
		int index = f.jComboBox1.getSelectedIndex();				
		if (index < 0)
			return;
		ListboxItem item = (ListboxItem) ((ComboboxModel)f.jComboBox1.getModel()).getElementAt(index);
		String name = item.getData();
		view.removeDatabase(f, name);		
	}

	public static void createTable() {
		if (f.jComboBox1.getSelectedIndex() < 0)
		{
			f.showMessageDialog("Hay chon Database", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		f.setEnabled(false);
		input.setVisible(true);
		input.type = 1;
		input.reset();
	}

	public static void deleteTable() {
		ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
        if (item == null)
            return;
        DefaultMutableTreeNode node = null;        
        TreePath path = f.jTree1.getSelectionPath();
        if (path != null){
            node = (DefaultMutableTreeNode) path.getLastPathComponent();            
        }
        if (node != null){            
            IconData data = (IconData) node.getUserObject();
            String tableName = (String) data.getData();
            view.deleteTable(f, item.getData(), tableName);
            return;                        	                    
        }		
	}

	public static void editDatabase() {
		// TODO Auto-generated method stub
		JOptionPane.showMessageDialog(f, "Edit Database", "Report", JOptionPane.INFORMATION_MESSAGE);		
	}

	public static void saveDatabase(boolean isSaveAll) {
		try {
			ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
			String db = item.getData();
			if (isSaveAll)
				view.saveDatabase(f, db);
			else
			{
				String tName = item.get_selectedTable();
				if (tName == null) {// Co the la save database
					view.saveDatabase(f, db);
					return;
				}
				
				int index = 0;
				while (index < f._tableHelper.size()){
					TableHelper helper = f._tableHelper.get(index);
					if (helper.databaseName.equals(db) && helper.tableName.equals(tName)){
						String title = f.jTabbedPane1.getTitleAt(f.jTabbedPane1.getSelectedIndex());
						title = title.substring(title.indexOf('-') + 1);							
						
						TableModel props = (TableModel)helper.modelProperty.getModel();
						List<List<String>> propsData = new ArrayList<List<String>>();
						for (int i = 0; i < props.getRowCount(); i++) {
							propsData.add(props.getRow(i));
						}
						
						TableModel datas = (TableModel)helper.modelData.getModel();
						List<List<String>> rows = new ArrayList<List<String>>();
						for (int i = 0; i < datas.getRowCount(); i++) {
							rows.add(datas.getRow(i));
						}
						view.saveTable(f, db, tName, propsData, rows);											
					}
					index++;
				}			
			}
		}
		catch (Exception e) {
			f.showMessageDialog(e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

	public static void inputAccept() {		
		changeForm();
		String data = input.getInputData();
		int type = input.type;
		switch(type){
		case 0:
			generateDatabase(data);
			break;
		case 1:
			generateTable(data);
			break;
		}
	}

	/*
	 * Trieu goi phat sinh 1 table moi
	 */
	private static void generateTable(String data) {
		ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
		String db = item.getData();
		view.createTable(f, db, data);		
	}

	/*
	 * Trieu goi phat sinh 1 database moi
	 */
	private static void generateDatabase(String data) {
		view.createDatabase(f, data);						
	}

	/*
	 * Thong bao cho biet user huy qua trinh nhap lieu
	 */
	public static void inputCancel() {
		changeForm();
	}
	
	/*
	 * Thay doi giua form nhap lieu va form chinh
	 */
	private static void changeForm(){
		input.setVisible(false);
		f.setEnabled(true);
	}

	/*
	 * Duoc trieu goi khi 1 node tren cay duoc chon
	 */
	public static void treeNodeSelectionChanged(TreeSelectionEvent e) {		
		ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
        if (item == null)
            return;
        DefaultMutableTreeNode node = null;
        TreePath path = e.getPaths()[0];
        if (path != null){
            node = (DefaultMutableTreeNode) path.getLastPathComponent();            
        }
        if (node != null){            
            IconData data = (IconData) node.getUserObject();
            String tableName = (String) data.getData();
            if (item.getData().equals(tableName)){
            	item.set_selectedTable(null);
            	return;
            }            	
            item.set_selectedTable(tableName);         
        }
	}

	public static String getSelectedDatabase(javax.swing.JComboBox c){
		if (c.getSelectedIndex() < 0)
			return null;
		ListboxItem item = (ListboxItem)c.getSelectedItem();
		String db = (String)item.getData();
		return db;	
	}
	
	public static int getIndexOf(String dbName, String tableName){
		int index = 0;
		List<TableHelper> helper = f._tableHelper;
		while (index < helper.size()){
			if (helper.get(index).databaseName.equals(dbName) && helper.get(index).tableName.equals(tableName))
				return index;
			index++;
		}
		return -1;
	}
	
	private static int getTab(String title){
		for (int i = 0; i < f.jTabbedPane1.getTabCount(); i++) {
			String t = f.jTabbedPane1.getTitleAt(i);
			if (t.equals(title))
				return i;			
		}
		return -1;
	}
	
	public static void initJTable(){
		ListboxItem item = (ListboxItem) f.jComboBox1.getSelectedItem();
        if (item == null || item.get_selectedTable() == null) {
        	f.showMessageDialog("Please select table first", "Error", JOptionPane.ERROR_MESSAGE);            
            return;
        }
        String dbName = item.getData();
        List<TableHelper> helper = f._tableHelper;
        String tableName = item.get_selectedTable();
        int index = getIndexOf(dbName, tableName);
        JTable property = null, data = null;
        /*
         * Chua co trong helper -> Khoi tao
         */
        if (index < 0){
        	index = helper.size();
        	property = createDesignTable();
        	data = createDataTable();
        	TableHelper h = new TableHelper(tableName, dbName, property, data); 
        	helper.add(h);
        	((TableModel)property.getModel()).set_helper(h);
        	((TableModel)data.getModel()).set_helper(h);
        }        
        else
        {
        	property = helper.get(index).modelProperty;
            if (property == null) {
            	property = createDesignTable();
            	data = createDataTable();
            	helper.get(index).modelProperty = property;
            	helper.get(index).modelData = data;
            	((TableModel)property.getModel()).set_helper(helper.get(index));
            	((TableModel)data.getModel()).set_helper(helper.get(index));
            }	
        }               
        JScrollPane scroll;                                              
        //int tabIndex = getTab(tableName+"-Design");
        if (f.jTabbedPane1.getTabCount() <= 0){                                	
        }
        else
        {
        	f.jTabbedPane1.removeAll();        	        
        }
        scroll = new JScrollPane(property);
    	f.jTabbedPane1.addTab(tableName+"-Design", null, scroll, tableName);
    	f.jTabbedPane1.setSelectedComponent(scroll);
    	return;
//        int i = JOptionPane.showConfirmDialog(f, "1 vai bang mo len chua duoc save, ban co muon save", "Warning", JOptionPane.YES_NO_OPTION);
//        //i = 0: thuc hien save xuong db
//        //i = 1: rollback tu db va tao tab moi
//        if (i == 0){
//        	String title = f.jTabbedPane1.getTitleAt(f.jTabbedPane1.getSelectedIndex());
//            title = title.substring(0, title.indexOf('-'));
//            view.saveTable(f, dbName, title);
//        }
//        else{
//        	f.jTabbedPane1.removeAll();
//        }
	}

	private static JTable createDataTable() {
		TableModel model = new TableModel();
		JTable table = new JTable(model);
		return table;
	}

	/**
	 * @return
	 */
	private static JTable createDesignTable() {		
		DesignTableModel design = new DesignTableModel();                        	  
		JTable table = new JTable(design);
		table.setRowHeight(20);
		table.setCellEditor(new DefaultCellEditor(new JTextField()));
		TableColumnModel tcm = table.getColumnModel();                        	
		TableColumn tc = tcm.getColumn(0);
		tc.setCellRenderer(new CheckboxRenderer());       
		tc.setCellEditor(new CheckboxEditor());
		tc = tcm.getColumn(2);
		tc.setCellRenderer(new ComboboxRenderer());
		tc.setCellEditor(new ComboboxEditor());
		return table;
	}
	
	/*
	 * Duoc trieu goi khi user click tren cay
	 */
	public static void treeMouseClick(MouseEvent e) {
		int selRow = f.jTree1.getRowForLocation(e.getX(), e.getY());
        TreePath selPath = f.jTree1.getPathForLocation(e.getX(), e.getY());        
        int btnIndex = e.getButton();        
        switch (btnIndex){
            case 1:
                if(selRow != -1) {
                    if(e.getClickCount() == 1) {
                        
                    }
                    else if(e.getClickCount() == 2) {
                        ListboxItem item = (ListboxItem) f.jComboBox1.getSelectedItem();                        
                        String tableName = item.get_selectedTable();
                        if (tableName == null)
                        	return; 
                        initJTable();                                                                       
                    }
                }
                break;
            case 3:
                if (selPath == null)
                    return;                
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)selPath.getLastPathComponent();                
                f.jTree1.setSelectionPath(selPath);
                DefaultTreeModel model = (DefaultTreeModel)f.jTree1.getModel();
                model.reload(node);
                break;            
        }
	}

	/*
	 * Duoc trieu goi khi user thay doi gia tri trong combobox
	 */
	public static void databaseChange(ItemEvent evt) {
		view.databaseChange(f, evt);
	}

	public static void editData() {
		ListboxItem item = (ListboxItem) f.jComboBox1.getSelectedItem();
        if (item == null || item.get_selectedTable() == null) {
        	f.showMessageDialog("Please select table first", "Error", JOptionPane.ERROR_MESSAGE);            
            return;
        }
        List<TableHelper> helper = f._tableHelper;
        String tableName = item.get_selectedTable();
        int index = getIndexOf(item.getData(), tableName);                                       
        JTable data = helper.get(index).modelData;
        if (data == null){
        	TableModel model = new TableModel();
        	data = new JTable(model);
        }
        JScrollPane scroll;                                              
        int tabIndex = getTab(tableName+"-Data");
        if (tabIndex < 0){                        
        	scroll = new JScrollPane(data);        	
        	f.jTabbedPane1.addTab(tableName+"-Data", null, scroll, tableName);
        	f.jTabbedPane1.setSelectedComponent(scroll);
        	return;
        }          
        f.jTabbedPane1.setSelectedIndex(tabIndex);
	}

	public static void initialize() {
		view.loadModel(f);
	}

	/*
	 * Thuc thi tao 1 dong moi trong bang hien hanh
	 */
	public static void createRow() {
		String title = f.jTabbedPane1.getTitleAt(f.jTabbedPane1.getSelectedIndex());
		int index = title.indexOf('-');
		ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
		String db = item.getData();
		String tableName = title.substring(0, index);
		String type = title.substring(index+1);
		index = 0;
		JTable table;
		while (index < f._tableHelper.size())
		{
			if (f._tableHelper.get(index).databaseName.equals(db) && f._tableHelper.get(index).tableName.equals(tableName.trim())){
				if (type.equals("Design"))
				{
					table = f._tableHelper.get(index).modelProperty;
					TableModel model = (TableModel)f._tableHelper.get(index).modelProperty.getModel();
					List<String> row = new ArrayList<String>();
					row.add("false");
					row.add("String");
					row.add("String");
					model.addRow(row);
					table.revalidate();
				}
				else
				{
					table = f._tableHelper.get(index).modelData;
					TableModel model = (TableModel) table.getModel();
					int col = model.getColumnCount();
					List<String> row = new ArrayList<String>();
					for (int i = 0; i < col; i++) {
						row.add(new String());
					}
					model.addRow(row);
					table.revalidate();
				}
				break;
			}
			index++;
		}		
	}

	public static void accountCancel() {
		af.setVisible(false);
		f.setEnabled(true);
	}

	public static void accountAccept(String text, String password) {
		af.setVisible(false);
		f.setEnabled(true);
		AccountStruct as = new AccountStruct();
		as.userName = text;
		as.pass = password;
		accountList.add(as);
	}

	public static void accountShow() {
		af.reset();
		af.setVisible(true);
		f.setEnabled(false);		
	}

	public static void deleteRow() {
		String title = f.jTabbedPane1.getTitleAt(f.jTabbedPane1.getSelectedIndex());
		int index = title.indexOf('-');
		ListboxItem item = (ListboxItem)f.jComboBox1.getSelectedItem();
		String db = item.getData();
		String tableName = title.substring(0, index);
		String type = title.substring(index+1);
		index = 0;
		JTable table;
		while (index < f._tableHelper.size())
		{
			if (f._tableHelper.get(index).databaseName.equals(db) && f._tableHelper.get(index).tableName.equals(tableName.trim())){				
				if (type.equals("Design"))
				{
					table = f._tableHelper.get(index).modelProperty;
					TableModel model = (TableModel)f._tableHelper.get(index).modelProperty.getModel();
					model.removeRow(table.getSelectedRow());
					table.revalidate();
				}
				else
				{
					table = f._tableHelper.get(index).modelData;
					TableModel model = (TableModel) table.getModel();
					model.removeRow(table.getSelectedRow());
					table.revalidate();
				}
				break;
			}
			index++;
		}		
	}
}